package com.stadium.tools;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;

/*
 * ehcache 缓存工具类
 */
public class EhcacheUtil {

	private static final CacheManager CACHE_MANAGER = CacheManager
			.getInstance();

	//创建ehcache 缓存，创建之后有效期是1个小时
	private static Cache cache = new Cache(new CacheConfiguration(
			"systemCache", 5000)
			.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO)
			.timeoutMillis(300).timeToLiveSeconds(60));
	//加载cache
	static{
		CACHE_MANAGER.addCache(cache);
	}
	
	//新增Item
	public static void putItem(String key,Object item){
		if(cache.get(key) !=null){
			cache.remove(key);
		}
		Element element = new Element(key, item);
		cache.put(element);
	}
	
	//移除key及对应的value
	public static void removeItem(String key){
		cache.remove(key);
	}
	
	//更新key及对应的value
	public static void updateItem(String key,Object item){
		putItem(key, item);
	}
	
	//根据key获取对应的value
	public static Object getItem(String key){
		Element element = cache.get(key);
		if(element != null){
			return element.getObjectValue();
		}
		return null;
	}
}
